// 使用对象存储常量
const CartConfig = {
	ITEM_CLASS: 'cart_item',
	LABEL_CLASS: 'cart_item_label',
	INPUT_CLASS_PARENT: 'cart_check_parent',
	INPUT_CLASS_CHILD: 'cart_check_child',
	INPUT_CLASS_CUSTOM: 'cart_item_input_custom',
	ITEM_PARENT_TITLE: 'cart_parent_title',
	ITEM_TOP: 'cart_list_content_top',
	ITEM_CONTENT_CLASS: 'cart_list_content',
	ITEM_CONTENT_IMG: 'cart_list_img',
	ITEM_TITLE_CLASS: 'cart_child_title',
	ITEM_TAG_BOX: 'cart_child_tag_box',
	ITEM_TAGS: 'cart_child_tags',

	ITEM_FOOTER_BOX: 'cart_child_footer_box',
	ITEM_GOODS_PRICE_BOX: 'goods_price',
	ITEM_GOODS_UNIT: 'unit',
	ITEM_GOODS_PRICE: 'price',
	ITEM_QUANTITY_BTN: 'btn_sub',
	ITEM_QUANTITY_NUM: 'number'
}

class ShoppingCart {
	constructor(options) {
		this.data = options.data;
		this.container = document.querySelector(options.container);
		this.onChangeParent = options.onChangeParent || function() {};
		this.onChange = options.onChange || function() {};
		this.onChangeCount = options.onChangeCount || function() {};
		this.allSelect = options.allSelect;
		this.init();
	}

	init() {
		this.render();
		this.addStyles();
		this.bindEvents();
	}

	render() {
		if (this.data.length == 0) return;
		this.container.innerHTML = '';
		const html = this.data.map((item, index) =>
			this.generateItem(item, index)
		).join('');
		this.container.innerHTML = html;

		this.updateCartStats();
	}

	generateItem(item, index) {
		const {
			shopName,
			promotionGoodsList
		} = item;

		const checkFlag = this.allSelect ? 'checked' : '';

		let childItemHtml = promotionGoodsList.map((e, i) => (`
		<label class="${CartConfig.LABEL_CLASS} ${CartConfig.ITEM_TOP}" data-shop-index="${index}" data-item-index="${i}">
			<input type="checkbox" class="${CartConfig.INPUT_CLASS_CHILD}"  ${checkFlag} data-price="${e.price}" data-shop-index="${index}" data-item-index="${i}"/>
			<span class="${CartConfig.INPUT_CLASS_CUSTOM}"></span>
			<img src="${e.thumb}" class="${CartConfig.ITEM_CONTENT_IMG}" />
			<section class="${CartConfig.ITEM_CONTENT_CLASS}">
				<span class="${CartConfig.ITEM_TITLE_CLASS}">${e.title}</span>
				<div class="${CartConfig.ITEM_TAG_BOX}">
				 	<span class="${CartConfig.ITEM_TAGS}">${e.specInfo[0].specValue},${e.specInfo[1].specValue}</span>
				</div>
				<div class="${CartConfig.ITEM_FOOTER_BOX}">
				 	<div class="${CartConfig.ITEM_GOODS_PRICE_BOX}">
				 		<span class="${CartConfig.ITEM_GOODS_UNIT}">¥</span>
				 		<span class="${CartConfig.ITEM_GOODS_PRICE}">${e.price}</span>
				 	</div>
				 	<span class="flex_1"></span>
				 	<input type="button" value="-" class="${CartConfig.ITEM_QUANTITY_BTN}" data-action="decrease" data-shop-index="${index}" data-item-index="${i}"/>
					<span class="${CartConfig.ITEM_QUANTITY_NUM}" >${e.quantity}</span>
				 	<input type="button" value="+" class="${CartConfig.ITEM_QUANTITY_BTN}" data-action="increase" data-shop-index="${index}" data-item-index="${i}"/>
				</div>
			</section>
		</label>`)).join('');

		let itemHtml = `<div class="${CartConfig.ITEM_CLASS}" data-index="${index}">
							<label class="${CartConfig.LABEL_CLASS}">
								<input type="checkbox" class="${CartConfig.INPUT_CLASS_PARENT}" data-shop-index="${index}"  ${checkFlag}/>
								<span class="${CartConfig.INPUT_CLASS_CUSTOM}"></span>
								<span class="${CartConfig.ITEM_PARENT_TITLE}">${shopName}</span>
							</label>
							${childItemHtml}
						</div>`;

		return itemHtml;
	}

	bindEvents() {
		// 使用事件委托监听容器内的change事件
		this.container.addEventListener('change', (e) => {
			if (e.target.classList.contains(CartConfig.INPUT_CLASS_PARENT)) {
				this.onParentCheckboxChange(e.target);
			} else if (e.target.classList.contains(CartConfig.INPUT_CLASS_CHILD)) {
				this.onChildCheckboxChange(e.target);
			}
		});

		// 监听数量按钮点击事件
		this.container.addEventListener('click', (e) => {
			const target = e.target;
			if (target.dataset.action === 'increase') {
				this.updateQuantity(target, 1);
			} else if (target.dataset.action === 'decrease') {
				this.updateQuantity(target, -1);
			}
		});
	}

	onParentCheckboxChange(checkbox) {
		const shopIndex = parseInt(checkbox.dataset.shopIndex);
		const childCheckboxes = this.container.querySelectorAll(
			`.${CartConfig.INPUT_CLASS_CHILD}[data-shop-index="${shopIndex}"]`
		);

		childCheckboxes.forEach(childCheckbox => {
			childCheckbox.checked = checkbox.checked;
			//this.updateCheckboxVisual(childCheckbox);
		});

		this.updateCartStats();
		this.onChangeParent('parent', shopIndex, checkbox.checked);
	}

	onChildCheckboxChange(checkbox) {
		const shopIndex = parseInt(checkbox.dataset.shopIndex);
		this.updateParentCheckboxState(shopIndex);
		this.updateCartStats();

		const itemIndex = parseInt(checkbox.dataset.itemIndex);
		this.onChange('child', shopIndex, itemIndex, checkbox.checked);
	}

	updateParentCheckboxState(shopIndex) {
		const parentCheckbox = this.container.querySelector(
			`.${CartConfig.INPUT_CLASS_PARENT}[data-shop-index="${shopIndex}"]`
		);
		const childCheckboxes = this.container.querySelectorAll(
			`.${CartConfig.INPUT_CLASS_CHILD}[data-shop-index="${shopIndex}"]`
		);
		const checkedCount = Array.from(childCheckboxes).filter(cb => cb.checked).length;

		if (checkedCount === 0) {
			parentCheckbox.checked = false;
			parentCheckbox.indeterminate = false;
		} else if (checkedCount === childCheckboxes.length) {
			parentCheckbox.checked = true;
			parentCheckbox.indeterminate = false;
		} else {
			parentCheckbox.checked = false;
			parentCheckbox.indeterminate = true;
		}

		//this.updateCheckboxVisual(parentCheckbox);
	}

	// updateCheckboxVisual(checkbox) {
	// 	const customCheckbox = checkbox.nextElementSibling;
	// 	if (checkbox.checked) {
	// 		customCheckbox.style.background = 'linear-gradient(135deg, #10b981, #059669)';
	// 	} else if (checkbox.indeterminate) {
	// 		customCheckbox.style.background = 'linear-gradient(135deg, #f59e0b, #d97706)';
	// 	} else {
	// 		customCheckbox.style.background = '#eee';
	// 	}
	// }

	updateQuantity(button, change) {
		console.log(button)
		const shopIndex = parseInt(button.dataset.shopIndex);
		const itemIndex = parseInt(button.dataset.itemIndex);

		const quantityElement = button.parentElement.querySelector(`.${CartConfig.ITEM_QUANTITY_NUM}`);
		let currentQuantity = parseInt(quantityElement.textContent);
		let newQuantity = currentQuantity + change;

		if (newQuantity < 1) newQuantity = 1;

		quantityElement.textContent = newQuantity;

		// 更新数据
		this.data[shopIndex].promotionGoodsList[itemIndex].quantity = newQuantity;

		this.updateCartStats();
		this.onChange('quantity', shopIndex, itemIndex, newQuantity);
	}

	updateCartStats() {
		let totalPrice = 0; //总价格
		let selectedCount = 0; //总商品件数
		let totalItems = 0; //总数量

		this.data.forEach((shop, shopIndex) => {

			const parentCheckbox = this.container.querySelector(
				`.${CartConfig.INPUT_CLASS_PARENT}[data-shop-index="${shopIndex}"]`
			);
			shop['checked'] = parentCheckbox.checked;

			shop.promotionGoodsList.forEach((item, itemIndex) => {
				const checkbox = this.container.querySelector(
					`.${CartConfig.INPUT_CLASS_CHILD}[data-shop-index="${shopIndex}"][data-item-index="${itemIndex}"]`
				);
				item['checked'] = checkbox.checked;

				if (checkbox && checkbox.checked) {
					totalPrice += item.price * item.quantity;
					selectedCount++;
				}
				totalItems += item.quantity;
			});
		});

		let allSelect = this.data.every(e => e.checked === true);
		this.onChangeCount(totalPrice, selectedCount, totalItems, allSelect);
	}

	setAllSelect(val) {
		this.allSelect = val;
		this.render();
	}

	addStyles() {
		this.styleElement = document.createElement('style');
		this.styleElement.textContent = `
		  
		  .${CartConfig.ITEM_CLASS} {
		  	position: relative;
		  	background: white;
		  	padding: var(--gap);
		  	margin-top: var(--gap);
		  	font-size: var(--font-size-primary);
		  }
		  
		  .${CartConfig.LABEL_CLASS} {
		  	display: flex;
		  	flex-direction: row;
		  	align-items: center;
		  }
		  
		  .${CartConfig.LABEL_CLASS} input[type="checkbox"] {
		  	display: none;
		  }
		  
		  .${CartConfig.LABEL_CLASS} .${CartConfig.INPUT_CLASS_CUSTOM}{
		  	display: inline-block;
		  	width: 20px;
		  	height: 20px;
		  	background: #eee;
		  	margin-right: var(--gap);
		  	border-radius: 50%;
		  	position: relative;
		  }
		  
		  .${CartConfig.LABEL_CLASS} input[type="checkbox"]:checked+.${CartConfig.INPUT_CLASS_CUSTOM} {
		  	background: green;
		  	-webkit-transition: all 0.15s ease-in;
		  	transition: all 0.15s ease-in;
		  }
		  
		  .${CartConfig.LABEL_CLASS} input[type="checkbox"]:checked+.${CartConfig.INPUT_CLASS_CUSTOM}::after {
		  	content: "";
		  	position: absolute;
		  	left: 7px;
		  	top: 3px;
		  	width: 5px;
		  	height: 10px;
		  	border: solid white;
		  	border-width: 0px 2px 2px 0px;
		  	transform: rotate(45deg);
		  }
		  
		  .${CartConfig.ITEM_PARENT_TITLE} {
		  	color: #333;
		  	font-size: 1.5rem;
		  	font-weight: bold;
		  }
		  
		  .${CartConfig.ITEM_TOP} {
		  	margin-top: var(--gap);
		  }
		  
		  .${CartConfig.ITEM_CONTENT_IMG} {
		  	width: 8.8rem;
		  	height: 8.8rem;
		  }
		  
		  .${CartConfig.ITEM_CONTENT_CLASS} {
		  	flex: 1;
		  	margin-left: 1rem;
		  	display: flex;
		  	flex-direction: column;
			
			.${CartConfig.ITEM_TITLE_CLASS} {
				color: #333;
				overflow-y: hidden;
				text-overflow: ellipsis;
				overflow: hidden;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
			}
			
			.${CartConfig.ITEM_TAG_BOX} {
				margin-top: 0.6rem;
			}
			
			.${CartConfig.ITEM_TAGS} {
				background-color: #f0f2f6;
				border-radius: 6px;
				padding: 2px;
				font-size: 1.0rem;
			}
			
			.${CartConfig.ITEM_FOOTER_BOX} {
				margin-top: 0.6rem;
				display: flex;
				flex-direction: row;
				align-items: center;
			
				.${CartConfig.ITEM_QUANTITY_NUM} {
					padding: 1.4rem;
					font-size: 1.2rem;
					color: #333;
				}
			
				.${CartConfig.ITEM_QUANTITY_BTN} {
					width: 2.8rem;
					height: 2.8rem;
					border-radius: 4px;
				}
			}
			
		  }
		  
		  .flex_1 {
		  	flex: 1;
		  }
		  
		`;

		document.head.appendChild(this.styleElement);
	}
}
